﻿var _Coupons;
var _UniqueCasinos = [];
var _Amounts = [];
var initialized = false;
var _Coupon = null;
var DAYS = (1000 * 60 * 60 * 24);
var _Sortable;
var _TabOrder = [];
var _Tabs;

$(function() {
	_Tabs = $("#tabs").tabs({
		cache: true
        , spinner: "<img src='Images/waiting_small.gif' border='0' /> Loading.."
        , ajaxOptions: { cache: true }

	});
	_Sortable = $("#tabs .ui-tabs-nav").sortable();
	_Sortable.bind("sortupdate", function() {
		_TabOrder = [];
		var li = $("ul li", _Tabs);
		for (var x = 0; x < li.length; x++) {
			_TabOrder.push($("a span",li[x]).html());
		}
	});
});


var Pages = {
	// EDIT CASINOS --------------------------------------------------------------------------------
	EditCasinos: {
		_Page: null,
		_initialized: false,
		Init: function() {
			if (Pages.EditCasinos._initialized) { return false; }
			Pages.EditCasinos.InitHandlers();
			var selCasinos = $(".selCasinos", Pages.EditCasinos._Page);
			if (selCasinos.children().length == 0) $("#pgEditCasinos .CasinosHeader").click();

			Pages.EditCasinos._Page = $("#pgEditCasinos");

			Pages.EditCasinos._initialized = true;

		},

		InitHandlers: function() {
			$("#pgEditCasinos .CasinosHeader").live("click", function() {
				var selCasinos = $("#pgEditCasinos .selCasinos");
				fillCasinos.Get({ ShowLoadingEl: selCasinos });
			});

			//-----------------------------------------------------------------------------------------
			$("[name='btnSave']", Pages.EditCasinos._Page).live("click", function() {
				ShowLoading("small", $("button[name='btnSave']", Pages.EditCasinos._Page));

				var params = [];
				params.CasinoID = $("[name='casinoID']").val();
				params.CasinoName = $("[name='casinoName']").val();

				CouponsAPI.Call(
                    { Method: "AddUpdateCasino"
                    , Params: params
                    , OnComplete: Pages.EditCasinos.UpdateComplete
                    , OnFail: RemoveLoading()
                    });
			});

			//-----------------------------------------------------------------------------------------
			$("[name='btnNew']", Pages.EditCasinos._Page).live("click", function() {
				$("[name='casinoID']").val("");
				$("[name='casinoName']").val("");
			});

			//-----------------------------------------------------------------------------------------
			$(".selCasinos", Pages.EditCasinos._Page).live("change", function() {
				$("[name='casinoID']").val($(this).val());
				$("[name='casinoName']").val($("option:selected", this).text());
			});

		},

		//-----------------------------------------------------------------------------------------
		UpdateComplete: function(results) {
			RemoveLoading();

			var result = eval("(" + results.d + ")");
			var StatusMessage = $("[name='StatusMessage']", Pages.EditCasinos._Page);
			StatusMessage.html(result.Message).fadeIn().delay(2000).fadeOut();

			if (result.Status == "success") {
				$("#pgEditCasinos .CasinosHeader").click();
			}
		}
	},

	// COUPONS -----------------------------------------------------------------------------------------
	Coupons: {
		_initialized: false,
		_Page: null,
		Init: function() {

			this._Page = $("#pgCoupons");


			if (Pages.Coupons._initialized == true) { return; }
			Pages.Coupons.InitHandlers();

			var _datePickerArgs = {
				showOn: 'button',
				buttonImage: 'Images/calendar.gif',
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true,
				showOtherMonths: true,
				selectOtherMonths: true,
				constrainInput: true,
				duration: 200,
				firstDay: 1
			};

			$("#StartDate, #EndDate", this._Page).datepicker(_datePickerArgs);
			//$("#ui-datepicker-div").each(function() { this.draggable({ opacity: 0.7, helper: 'clone' }); });
			$("#btnGo", this._Page).button();
			$("#btnAdvancedSearch", this._Page).button();
			$("#Gotten", this._Page).button();
			$("#NotGotten", this._Page).button();

			Pages.Coupons._initialized = true;

			var dt = new Date();
			$("#StartDate").val(dt.getMonth() + 1 + "/" + dt.getDate() + "/" + dt.getFullYear());
			$("#EndDate").val($("#StartDate").val());
		},

		//----------------------------------------------------------------------------------------------------
		InitHandlers: function() {
			$("#btnGo", this._Page).live("click", function() {
				var curPage = Pages.Coupons._Page;
				ShowLoading("small", $("div#Coupons", curPage));

				var params = [];
				var AS = ($("#AdvancedSearch", curPage).css("display") != "none");

				params.StartDate = $("#StartDate", curPage).val();
				params.EndDate = $("#EndDate", curPage).val();
				params.CasinoID = (AS ? $("#AdvancedSearch select.selCasinos", curPage).val() : "");
				params.AmountMin = (AS ? $("#AmountMin", curPage).val() : "");
				params.AmountMax = (AS ? $("#AmountMax", curPage).val() : "");
				params.Gotten = (AS ? $("#Gotten", curPage).is(":checked") : "");
				params.NotGotten = (AS ? $("#NotGotten", curPage).is(":checked") : "true");
				params.OrderBy = $("#CouponOrderBy").val();

				CouponsAPI.Call(
                    { Method: "GetCoupons"
                    , Params: params
                    , OnComplete: Pages.Coupons.GetCoupons_Complete
                    , OnFail: RemoveLoading()
                    });
			});

			//----------------------------------------------------------------------------------------------------
			$("#btnAdvancedSearch", this._Page).live("click", function() {
				$("#AdvancedSearch", this._Page).slideToggle("fast");
				var selCasinos = $("#AdvancedSearch .selCasinos", Pages.Coupons._Page);
				if (selCasinos.html() == "") fillCasinos.Get({ ShowLoadingEl: selCasinos });
			});

			//----------------------------------------------------------------------------------------------------
			$("input[id*='tglGotten']", this._Page).live("change", function() {
				var $this = $(this);
				var Label = $this.siblings("label.Casino").children("span").eq(0);
				ShowLoading("small", Label);

				var params = [];
				params.CouponID = $this.closest("tr").attr("couponid");
				params.Gotten = $this.is(":checked");

				var UpdateGotten_Complete = function(data) {
					RemoveLoading();
					var results = eval("(" + data.d + ")");
					if (results.status == "success") {
						var OldHtml = Label.html();
						Label.html("Updated!");
						Label.css("background-color", "khaki");
						Label.fadeOut(1000,
                            function() {
                            	Label.html(OldHtml).css("background-color", "transparent").show();
                            	$("#btnGo", Pages.Coupons._Page).click();
                            });


					}
				};

				CouponsAPI.Call(
                    { Method: "UpdateGotten"
                    , Params: params
                    , OnComplete: UpdateGotten_Complete
                    , OnFail: RemoveLoading()
                    });


			});

			//----------------------------------------------------------------------------------------------------
			$(".CasinoLabel").live("click", function() {
				var OrderBy = $("#CouponOrderBy")
				var OrderByVal = OrderBy.val();

				if (OrderByVal != "CasinoName") {
					OrderBy.val("CasinoName");
				}
				else {
					OrderBy.val("CasinoName desc");
				}

				$("#btnGo").click();
			});

			//----------------------------------------------------------------------------------------------------
			$(".DateHeaderContainer").live("click", function() {
				var OrderBy = $("#CouponOrderBy")
				var OrderByVal = OrderBy.val();

				if (OrderByVal != "StartDate") {
					OrderBy.val("StartDate");
				}
				else {
					OrderBy.val("StartDate desc");
				}

				$("#btnGo").click();
			});

			//----------------------------------------------------------------------------------------------------
			$(".Coupon").live("click", function() {
				var CouponContainer = $(this).parent();
				var html = [];
				var editCoupon = $(".editCoupon");
				var editCouponHTML;
				if (editCoupon.length == 0) {
					editCouponHTML = createEditCouponForm();
				}
				else {
					editCouponHTML = "<div class='editCoupon'>" + editCoupon[0].innerHTML + "</div>";
					var oldEditCoupon = editCoupon;
				}

				CouponContainer.append(editCouponHTML);

				editCoupon = CouponContainer.children(".editCoupon:first");

				var this_left = $(this).css("left");

				var _datePickerArgs = {
					//showOn: 'button',
					//buttonImage: 'Images/calendar.gif',
					//buttonImageOnly: true,
					changeMonth: true,
					changeYear: true,
					showOtherMonths: true,
					selectOtherMonths: true,
					constrainInput: true,
					duration: 200,
					firstDay: 1
				};

				editCoupon.css({ "left": this_left, "display": "block" });
				editCoupon.hide();

				var inputs = editCoupon.find("#editStartDate, #editEndDate")
				inputs.datepicker(_datePickerArgs);

				var curCouponTR = CouponContainer.closest("tr");

				$(inputs[0]).val(curCouponTR.attr("startdate"));
				$(inputs[1]).val(curCouponTR.attr("enddate"));
				editCoupon.find("#editAmount").val(curCouponTR.attr("amount"));

				if (oldEditCoupon) {
					oldEditCoupon.slideUp("normal", function() {
						oldEditCoupon.remove();
						editCoupon.slideDown();
					});
				}
				else {
					editCoupon.slideDown();
				}

			});

			//----------------------------------------------------------------------------------------------------
			$("#btnEditCouponCancel").live("click", function() {
				$(this).closest(".editCoupon").slideUp();
			});

			//----------------------------------------------------------------------------------------------------
			$("#btnEditCouponSave").live("click", function() {
				var jqThis = $(this);
				if (jqThis.hasClass("ui-state-disabled")) { return false; }
				jqThis.addClass("ui-state-disabled");
				jqThis.attr("disabled", "disabled");
				jqThis.children("span").html("Saving...<img src='Images/waiting_small.gif'/>");

				var ajaxSuccess = function(results) {
					results = eval("(" + results.d + ")");
					if (results.Status == "success") {
						jqThis.children("span").html("SUCCESS!");
						$("#btnGo").click();
					}
					else {
						jqThis.removeAttr("disabled");
						jqThis.removeClass("ui-state-disabled");
						jqThis.children("span").html("Save");
						$("<div>Save Failed:<br>" + results.Message + "<br></div>")
							.dialog(
							{
								modal: true
								, buttons:
								{
									OK: function() { $(this).dialog("close"); }
								}
							}
						);
					}
				}

				var CouponTR = jqThis.closest("tr");
				var params = [];
				params.sCouponID = CouponTR.attr("couponid");
				params.sStartDate = CouponTR.find("#editStartDate").val();
				params.sEndDate = CouponTR.find("#editEndDate").val();
				params.sAmount = CouponTR.find("#editAmount").val();


				CouponsAPI.Call(
						{ Method: "UpdateCoupon"
						, Params: params
						, OnComplete: ajaxSuccess
						, OnFail: RemoveLoading()
						});
			});

		},

		//----------------------------------------------------------------------------------------------------
		GetCoupons_Complete: function(results) {
			_Coupons = eval("(" + results.d + ")");

			if (_Coupons.failed) {
				$("#Coupons").html(_Coupons.failed);
				return false;
			}
			var W = $("#Coupons", Pages.Coupons._Page).width() - 160;
			//W = 1100;
			var StartDate = new Date("1/1/3000");
			var EndDate = new Date("1/1/1900");
			var NotGottenTotal = 0;
			var GottenTotal = 0;

			for (var x = 0; x < _Coupons.length; x++) {
				var NewStartDate = new Date(_Coupons[x].StartDate);
				var NewEndDate = new Date(_Coupons[x].EndDate);
				if (NewStartDate - StartDate < 0) StartDate = NewStartDate;
				if (NewEndDate - EndDate > 0) EndDate = NewEndDate;
			}
			var CouponLabelWidth = 100;
			var sStartDate = StartDate.getMonth() + 1 + "/" + StartDate.getDate();
			var sEndDate = EndDate.getMonth() + 1 + "/" + EndDate.getDate();
			var DayRange = parseInt(Math.abs((StartDate - EndDate) / DAYS) + 1);
			var DayPixel = parseInt(W / DayRange);

			var html = [];

			html.push("<table><tr><td><div class='CasinoLabel'>Casino:</div></td>"
                , "<td class='CouponHeader' style='width:", W, "px'>"
                    , "<div class='DateHeaderContainer'>"
                        , "<div class='StartLabel BoldDate'>", sStartDate, "</div>");

			var CurMonth = StartDate.getMonth() + 1;
			for (var x = 2; x <= DayRange; x++) {

				var CurDate = new Date(StartDate);
				CurDate.setDate(CurDate.getDate() + (x - 1));
				var sCurDate, sCurClass, Total = 0;
				if (CurDate.getMonth() + 1 != CurMonth) {
					CurMonth = CurDate.getMonth() + 1;
					sCurDate = CurMonth.toString() + "/" + CurDate.getDate();
					sCurClass = "MiddleDateHeader BoldDate";
				}
				else {
					sCurDate = CurDate.getDate();
					sCurClass = "MiddleDateHeader";
				}

				html.push("<div class='", sCurClass, "' style='left:"
                    , parseInt(((x - 1) * (DayPixel)).toString()), "px'>"
                    , sCurDate
                    , "</div>");
			}
			html.push("</div></td></tr>");


			for (var x = 0; x < _Coupons.length; x++) {

				var curCoupon = _Coupons[x];
				var CouponStartDate = new Date(curCoupon.StartDate);
				if (CouponStartDate.valueOf() < StartDate.valueOf()) CouponStartDate = StartDate;
				var CouponEndDate = new Date(curCoupon.EndDate);

				var CouponDateRange = parseInt(Math.abs((CouponStartDate - CouponEndDate) / DAYS));
				var CouponStartOffSet = parseInt(Math.abs((StartDate - CouponStartDate) / DAYS));
				var CouponLeft = parseInt((DayPixel * CouponStartOffSet).toString());
				if (CouponEndDate.valueOf() > EndDate.valueOf()) {
					CouponEndDate = EndDate;
					CouponDateRange += 1;
				}
				var CouponWidth = parseInt((DayPixel * CouponDateRange).toString()) + 10;
				if (CouponWidth < 25) { CouponWidth = 25; }
				var curStartDate = new Date(curCoupon.StartDate);
				var curEndDate = new Date(curCoupon.EndDate);
				var sCurStartDate = curStartDate.getDate();
				var sCurEndDate = curEndDate.getDate();
				var numDays = curEndDate - curStartDate;
				(curCoupon.Gotten ? GottenTotal += curCoupon.Amount : NotGottenTotal += curCoupon.Amount);

				html.push(
                    "<tr couponid='", curCoupon.CouponID, "' startdate='" + curCoupon.StartDate + "' enddate='" + curCoupon.EndDate + "' amount='" + curCoupon.Amount + "'>"
                        , "<td>"
                            , "<label for='tglGotten", curCoupon.CouponID, "' class='Casino'>"
                                , curCoupon.CasinoName
                            , "</label>"
                            , "<input type='checkbox' id='tglGotten", curCoupon.CouponID, "' ", (curCoupon.Gotten ? "checked" : ""), ">"
                    , "</td>"
                    , "<td>"
                        , "<div class='CouponContainer'>"
                            , "<div class='Coupon", (curCoupon.Gotten ? " Gotten" : ""), "' style='left:", CouponLeft, "px; width:", CouponWidth + 5, "px'>"
                                , "<div class='CouponStartDate'>", sCurStartDate, "</div>"
                                , "&nbsp;"
                                , "<div class='CouponDollar'>$", curCoupon.Amount, "</div>"
                                , (numDays > 0 ? "<div class='CouponEndDate'>" + sCurEndDate + "</div>" : "")
                            , "</div>"
                        , "</div>"
                    , "</td></tr>");
			}
			html.push("</table>");
			$("#Coupons").html(html.join(""));
			$("div#CouponsHeader #lblGottenAmount").html("$" + GottenTotal);
			$("div#CouponsHeader #lblNotGottenAmount").html("$" + NotGottenTotal);
			$("div#CouponsHeader #lblCount").html(_Coupons.length);
			$("input[id*='tglGotten']", Pages.Coupons._Page).button();
			$(".CasinoLabel", Pages.Coupons._Page).button();
			RemoveLoading();
		}

	},
	//ADD COUPONS ---------------------------------------------------------------------------------
	AddCoupons: {
		_initialized: false,
		_Page: null,

		Init: function() {
			if (Pages.AddCoupons._initialized == true) { return; }
			this._Page = $("#pgAddCoupons");
			Pages.AddCoupons.InitHandlers();

			var datepicker_args = {
				showOn: 'button',
				buttonImage: 'Images/calendar.gif',
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true,
				showOtherMonths: true,
				selectOtherMonths: true,
				constrainInput: true,
				duration: 200,
				firstDay: 1

			};
			$("#pgAddCoupons_StartDate, #pgAddCoupons_EndDate").datepicker(datepicker_args)
			//$("#ui-datepicker-div").each(function() { this.draggable({ opacity: 0.7, helper: 'clone' }); });
			$("#btnSave", Pages.AddCoupons._Page).button();
			$("#btnClear", Pages.AddCoupons._Page).button();

			var selCasinos = $(".selCasinos", Pages.AddCoupons._Page);
			if (selCasinos.children().length == 0) fillCasinos.Get({ ShowLoadingEl: selCasinos });

			Pages.AddCoupons._initialized = true;

		},

		//----------------------------------------------------------------------------------------------------
		InitHandlers: function() {
			$("#btnSave", Pages.AddCoupons._Page).live("click", function() {
				var FormFields = $(".formField", Pages.AddCoupons._Page);
				var StatusMsg = $("#StatusMsg", Pages.AddCoupons._Page);
				FormFields.css("backgroundColor", "white");
				StatusMsg.html("");

				var StartDate = $("#pgAddCoupons_StartDate", Pages.AddCoupons._Page);
				var EndDate = $("#pgAddCoupons_EndDate", Pages.AddCoupons._Page);
				var Casino = $(".selCasinos", Pages.AddCoupons._Page);
				var Amount = $("#Amount", Pages.AddCoupons._Page);
				Amount.val(Amount.val().replace("$", ""));
				var Gotten = $("#Gotten", Pages.AddCoupons._Page);
				var err = [];

				var dtStartDate = new Date(StartDate.val());
				var dtEndDate = new Date(EndDate.val());

				if (dtStartDate.toDateString() == "Invalid Date"
                        || dtStartDate.getFullYear() < 2000
                        || dtStartDate.getFullYear() > 2050
                   ) {
					err.push({ msg: "-Start Date must be a valid date.", El: StartDate })
				}
				if (dtEndDate.toDateString() == "Invalid Date"
                        || dtEndDate.getFullYear() < 2000
                        || dtEndDate.getFullYear() > 2050
                   ) {
					err.push({ msg: "-End Date must be a valid date.", El: EndDate })
				}
				else if (dtEndDate.valueOf() < dtStartDate.valueOf()) {
					err.push({ msg: "-End Date must be greater than or equal to start date.", El: EndDate })
				}
				if (Casino.val() == "") {
					err.push({ msg: "-You must select a casino.", El: Casino })
				}
				if (Amount.val() == "" || isNaN(Amount.val())) {
					err.push({ msg: "-Amount must be a valid number.", El: Amount })
				}

				StatusMsg.show();
				if (err.length > 0) {
					var sErr = "";
					for (var x = 0; x < err.length; x++) {
						sErr += err[x].msg + "<br>";
						err[x].El.css("backgroundColor", "pink");
					}
					sErr = sErr.substring(0, sErr.length - 4);
					StatusMsg.css("backgroundColor", "pink");
					StatusMsg.html(sErr);
				}
				else {
					StatusMsg.css("backgroundColor", "Khaki");
					StatusMsg.html("Saving... <img src='Images/waiting_small.gif'/>");
					var params = [];
					params.CasinoID = Casino.val();
					params.StartDate = StartDate.val();
					params.EndDate = EndDate.val();
					params.Amount = Amount.val();
					params.Gotten = Gotten.is(":checked");

					CouponsAPI.Call({
						Method: "SaveCoupon"
                        , Params: params
                        , OnComplete: function(data) {
                        	var status = eval("(" + data.d + ")");
                        	if (status.msg = "success") {
                        		StatusMsg.css("backgroundColor", "lightgreen");
                        		StatusMsg.html("Coupon saved!");
                        		StatusMsg.fadeOut(9000);
                        		var NewRow = [];
                        		NewRow.push("<div class='AddedCoupon'>"
                                    , Casino.children("option:selected").text()
                                    , " "
                                    , StartDate.val()
                                    , " - "
                                    , EndDate.val()
                                    , " : $"
                                    , Amount.val()
                                    , " "
                                    , (Gotten.is(":checked") ? " Gotten" : " Not Gotten")
                                    , "</div>");
                        		$("#AddedCoupons").prepend(NewRow.join(""));
                        	}
                        	else {
                        		StatusMsg.css("backgroundColor", "yellow");
                        		StatusMsg.html("Save Failed! : " + status);
                        	}
                        }
                        , OnFail: function() {
                        	StatusMsg.css("backgroundColor", "yellow");
                        	StatusMsg.html("Save Failed! : General Failure. Cause Unknown.");
                        	RemoveLoading();
                        }
					});
				}
			});

			//-----------------------------------------------------------------------------------------------------
			$("#btnClear", Pages.AddCoupons._Page).live("click", function() {
				var StartDate = $("#pgAddCoupons_StartDate", Pages.AddCoupons._Page);
				var EndDate = $("#pgAddCoupons_EndDate", Pages.AddCoupons._Page);
				var Casino = $(".selCasinos", Pages.AddCoupons._Page);
				var Amount = $("#Amount", Pages.AddCoupons._Page);
				Amount.val(Amount.val().replace("$", ""));
				var Gotten = $("#Gotten", Pages.AddCoupons._Page);

				StartDate.val("");
				EndDate.val("");
				Casino.val("");
				Amount.val("");
				Gotten.attr("checked", false);
			});

			$("#pgAddCoupons_StartDate, #pgAddCoupons_EndDate", Pages.AddCoupons._Page).live("blur", function() {
				var StartDate = $("#pgAddCoupons_StartDate", Pages.AddCoupons._Page);
				var EndDate = $("#pgAddCoupons_EndDate", Pages.AddCoupons._Page);

				var arrStartDate = StartDate.val().split("/");
				var arrEndDate = EndDate.val().split("/");

				if (arrStartDate.length > 2 && arrStartDate[2].length < 4)
					StartDate.val(arrStartDate[0] + "/" + arrStartDate[1] + "/" + "20" + arrStartDate[2]);

				if (arrEndDate.length > 2 && arrEndDate[2].length < 4)
					EndDate.val(arrEndDate[0] + "/" + arrEndDate[1] + "/" + "20" + arrEndDate[2]);

			});
		}
	}
}


